import { getOrderLease, prepaymentPay} from "../../../api/order";
import { getBankCard,readyPay,confirmPay } from "../../../api/bank";
Page({
  data: {
    order_id: '',
    billData: {},
    isView: false,
    order_lease: [],
    selectedList: [],
    bankList:[],
    totalPrice: 0,
    codeName: '获取验证码',
    totalTime1: 60,
    isSend1: false, //禁用
    timer: '', //定时器
    payCode: '',
    flowIndex: -1,
    flowList:[],
    flowNo: '',
    placeholder: '请填验证码',
    disabledInput: false,
    unique_code2:'',
    unique_code3:'',
    confirmPay:''
  },
  onLoad(options) {
    this.setData({ order_id: options.order_id, isView: !!options.isView });
    my.setNavigationBar({
      title: this.data.isView ? '账单详情' : '立即还款'
    });
    this.getData();
  },
  onShow(){
    this.getData();
  },
  getStatusName(status) {
    switch (status) {
      case 0:
        return '未还款';
      case 1:
        return '已还款';
      case 2:
        return '已退款';
      case 3:
        return '已买断';
      case 4:
        return '已逾期';
      case 5:
        return '线下支付';

      default:
        break;
    }
  },
  getData() {
    getOrderLease(this.data.order_id).then(res => {
      let total = 0;
      const obj = { ...res };
      const list = [];
      obj.order_lease.forEach(element => {
        element.statusName = this.getStatusName(element.status);
        element.checked = false;
        if (element.status == 0 || element.status == 4) {
          element.checked = true;
          total += parseFloat(element.rent);
          list.push(element.id);
        }
      });
      console.log(obj.order_lease);
      this.setData({
        billData: obj || {},
        order_lease: obj.order_lease || [],
        selectedList: list,
        totalPrice: total.toFixed(2)
      })
    })
  },
  onCheckChange(e) {
    const { id } = e.currentTarget.dataset;
    const { value } = e.detail;
    const { order_lease } = this.data;
    let total = 0;
    const list = [];
    order_lease.forEach(element => {
      if (element.id == id) {
        element.checked = value;
      }
      if (element.checked) {
        list.push(element.id);
        total = total + parseFloat(element.rent);
      }
    })
    this.setData({ order_lease, selectedList: list, totalPrice: total.toFixed(2) });
  },
  closeModal() {
    this.setData({
      flowModal: false
    })
  },
  bindPickerChange(e) {
    this.setData({
      flowIndex: e.detail.value,
      unique_code2:this.data.flowList[e.detail.value].value
    });
   
  },
  partialRepayment(e){
    my.navigateTo({ url: '../partial/partial?orderId='+this.data.order_id+'&leaseId='+ e.target.dataset.leaseId});
  },
  submit() {

    my.showActionSheet({
      title: '支付方式',
      items: ['支付宝', '银行卡支付'],
      cancelButtonText: '取消',
      success: (res) => {
       if(res.index==1){
     
        getBankCard().then(res => {
          console.log(res);
          if(res==''){
            my.showToast({
              type: 'fail',
              content: '暂未绑卡，前往绑卡',
              duration: 200,
            });
            my.navigateTo({ url: '../bankCard/addBank/addBank' });
            return;
           }
           this.setData({flowModal:true});
          let list = []
          let flowList = []
          for (let item in res) {
            list.push(res[item].bank_name + res[item].card_no);
            flowList.push({name:res[item].card_no,value: res[item].id});
          }
          this.setData({bankList:list});
          this.setData({flowList:flowList});
        })
     }
        if(res.index==0){
          const { order_id: orderId, selectedList, order_lease } = this.data;
          for (let item of selectedList) {
            for (let ol of order_lease) {
              if (item == ol.id) {
                break;
              }
              // if ((ol.status == 0 || ol.status == 4) && !ol.checked) {
              //   my.showToast({
              //     type: 'fail',
              //     content: '还款需按顺序还款，不能跳期还款',
              //     duration: 1000,
              //   });
              //   return;
              // }
            }
          }
          const leaseId = selectedList.join(',');
          prepaymentPay({ orderId, leaseId }).then(res => {
            if (res.tradeNo) {
              my.tradePay({
                tradeNO: res.tradeNo,
                success: (res) => {
                  if (res.resultCode == 9000) {
                    my.reLaunch({
                      url: '../paySuccess/paySuccess?orderId=' + orderId
                    });
                  } else {
                    my.showToast({
                      type: 'fail',
                      content: '支付失败，请稍后重试',
                      duration: 1000,
                    });
                  }
                }
              });
            }
          })
        }
      },
    });
  },
  onFlowCode(e) {
    this.setData({ payCode: e.detail.value })
  },
  goPay1(){
    // if(this.data.payCode==''){
    //   my.showToast({
    //     content:"请先输入验证码",
    //     type:'error'
    //   })
    //   return
    // }
    let data1={
      leaseId:this.data.selectedList,
      orderId:this.data.order_id,
      unique_code3:this.data.unique_code3,
      code:this.data.payCode,
      unique_code2: this.data.unique_code2,
    }
    
    confirmPay(data1).then(res=>{
      my.showToast({
        content:"支付成功",
        type:'success'
      })
      this.closeModal();
      this.getData();
      this.setData({isView:false});
    })
  },
	handleCode() {
    let data = {
      unique_code2: this.data.unique_code2,
      leaseId:this.data.selectedList,
      orderId:this.data.order_id,
    }
    if (this.data.unique_code2 == '') {
      my.showToast({
        content: "请先选择银行卡",
        icon: 'fail'
      })
      return
    }
    readyPay(data).then(res => {
      this.setData({unique_code3: res.UniqueCode});  

      this.setData({isSend1: true,codeName:this.data.totalTime1 + 's后重新发送'});
      this.data.timer1 = setInterval(() => {
        this.data.totalTime1--
        this.setData({codeName:this.data.totalTime1 + 's后重新发送'}); 
  
        if (this.data.totalTime1 < 0) {
          clearInterval(this.data.timer1)
          this.setData({codeName:'重新发送验证码',totalTime1:60,isSend1:false}); 
        }
      }, 1000)
     })

  },

});
